package com.example.demo.service;

import com.example.demo.core.ApiResponse;
import com.example.demo.core.base.BaseService;
import com.example.demo.dao.UserRepository;
import com.example.demo.dto.TokenInfoDto;
import com.example.demo.dto.LoginDto;
import com.example.demo.entity.User;
import com.example.demo.util.AssertUtils;
import com.example.demo.util.CaptchaUtils;
import com.example.demo.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService extends BaseService<User, Long> {

    private final UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private TokenUtils tokenUtils;

    public UserService(UserRepository userRepository) {
        super(userRepository);
        this.userRepository = userRepository;
    }

    public ApiResponse<TokenInfoDto> createToken(LoginDto dto) {
        AssertUtils.isTrue(CaptchaUtils.verify(dto.getKey(), dto.getCode()), "验证码错误");
        User user = userRepository.findByUsername(dto.getUsername());
        AssertUtils.isTrue(user != null && passwordEncoder.matches(dto.getPassword(), user.getPassword()), "用户名或密码错误");
        // 生成token
        String accessToken = tokenUtils.createToken(dto.getUsername());
        String refreshToken = tokenUtils.refreshToken(accessToken);
        return ApiResponse.ok(new TokenInfoDto(accessToken, refreshToken));
    }

    public ApiResponse<TokenInfoDto> refreshToken(String oldRefreshToken) {
        //校验refreshToken，如果令牌没有过期
        if (tokenUtils.isTokenExpired(oldRefreshToken)) {
            return ApiResponse.fail("刷新令牌已过期，请重新登录！");
        }
        //解析refreshToken
        String username = tokenUtils.getUsernameFromToken(oldRefreshToken);
        //生成新的accessToken
        String newAccessToken = tokenUtils.createToken(username);
        String newRefreshToken = tokenUtils.refreshToken(newAccessToken);
        return ApiResponse.ok("令牌请求成功！", new TokenInfoDto(newAccessToken, newRefreshToken));
    }
}
